﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DoubleH.Utility;
using System.Collections.ObjectModel;
using Table=FCNS.Data.Table;
using System.Data;
using FCNS.Data;
using DoubleH.Utility.Configuration;
using System.Collections;
using System.Diagnostics;

namespace StoreS
{
    /// <summary>
    /// PanDian.xaml 的交互逻辑
    /// </summary>
    public partial class PanDian : Window
    {
        enum Flag
        {
            盘点准备单,
            开始盘点
        }

        Flag flag = Flag.盘点准备单;
        List<TempClass> productInList = new List<TempClass>();
        Table.CheckStoreS order = null;

        public PanDian()
        {
            InitializeComponent();

            InitEvent();
        }

        public void Init(Table.CheckStoreS obj)
        {
            InitVar();

            dataGridObject.Init(DoubleHConfig.UserConfig.GetUserUIparams(DataTableText.盘点单据商品编辑));
            order = obj ?? new Table.CheckStoreS();
            if (order.Id == -1)
                PanDianReady();
            else
                PanDianing();

            dataGridObject.ShowBottom = false;
            dataGridObject.ShowBodyContexMenu = false;
            dataGridObject.CanUserAddRows = false;
        }

        private void InitVar()
        {
            checkComboBoxBrand.ItemsSource = Table.UniqueS.GetList(Table.UniqueS.EnumFlag.品牌, Table.UniqueS.EnumEnable.启用);
            checkComboBoxBrand.DisplayMemberPath = "Name";
            checkComboBoxBrand.ValueMemberPath = "Id";
            checkComboBoxPlace.ItemsSource = Table.UniqueS.GetList(Table.UniqueS.EnumFlag.产地, Table.UniqueS.EnumEnable.启用);
            checkComboBoxPlace.DisplayMemberPath = "Name";
            checkComboBoxPlace.ValueMemberPath = "Id";
            checkComboBoxGroupS.ItemsSource = Table.GroupS.GetList(Table.GroupS.EnumFlag.商品分类, Table.GroupS.EnumEnable.启用);
            checkComboBoxGroupS.DisplayMemberPath = "Name";
            checkComboBoxGroupS.ValueMemberPath = "Id";
        }

        private void InitEvent()
        {
            panDianReady.Click += (ss, ee) => PanDianReady();
            panDianStart.Click += (ss, ee) => PanDianStart();
            panDianEnd.Click += (ss, ee) => PanDianEnd();
            panDianZuoFei.Click += (ss, ee) => PanDianZuoFei();
            buttonOK.Click += (ss, ee) => Search();
            buttonPrint.Click += (ss, ee) => PrintOrSave();

            textBoxSearch.KeyDown += (ss, ee) =>
            {
                if (ee.Key == Key.Enter)
                    SearchText();
            };
        }

        private void PanDianReady()
        {
            buttonPrint.Content = "打印";

            flag = Flag.盘点准备单;
            labelTitle.Content = flag.ToString();

            dataGridObject.IsReadOnly = true;
        }

        private void PanDianStart()
        {
            if (productInList.Count == 0)
            {
                MessageWindow.Show("请查询需要盘点的商品.");
                return;
            }

            PanDianStart pds = new PanDianStart();
            pds.ShowDialog();
            if (!pds.OrderDateTime.HasValue)
                return;

            order.OrderDateTime = pds.OrderDateTime.Value;
            order.StoreSId = uCStoreS1.SelectedObjectId;
            foreach (TempClass tc in productInList)
                order.ProductSList.Add(new Table.ProductSInCheckStoreS()
                {
                    OrderNO = order.OrderNO,
                    ProductSId = tc._ProductSId,
                    QuantityNew = 0,
                    QuantityOld = tc._QuantityOld,
                    AveragePrice = tc._AveragePrice
                });

            Table.DataTableS.EnumDatabaseStatus result = order.Insert();
            if (result != Table.DataTableS.EnumDatabaseStatus.操作成功)
            {
                MessageWindow.Show(result.ToString());
                return;
            }

            MessageWindow.Show("盘点开始");
            PanDianing();
        }

        private void PanDianing()
        {
            buttonPrint.Content = "保存";

            flag = Flag.开始盘点;
            labelTitle.Content = flag.ToString();

            List<Int64> productSId = new List<long>();
            foreach (Table.ProductSInCheckStoreS p in order.ProductSList)
                productSId.Add(p.ProductSId);

            productInList = FillProductS(Table.ProductS.GetList(productSId.ToArray()));
            productInList.ForEach(f =>  f._QuantityNew = (order.ProductSList.First(f2 => f2.ProductSId == f._ProductSId).QuantityNew));
            dataGridObject.ItemsSourceNoCalc = productInList;
            dataGridObject.IsReadOnly = false;
        }

        private void PanDianEnd()
        {
            if (order.Id == -1)
            {
                MessageWindow.Show("盘点未开始");
                return;
            }
            else if (order.Enable == Table.CheckStoreS.EnumEnable.盘点结束)
            {
                MessageWindow.Show("盘点已结束");
                return;
            }
            else if (MessageWindow.Show("", "确定要结束盘点吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                MessageWindow.Show(order.ShenHe().ToString());
                this.Close();
            }
        }

        private void PanDianZuoFei()
        {
            if (order.Id == -1)
            {
                MessageWindow.Show("盘点未开始");
                return;
            }

            MessageWindow.Show(order.ZuoFei().ToString()); 
            this.Close();
        }

        private void Search()
        {
            switch (flag)
            {
                case Flag.开始盘点:
                    if (!string.IsNullOrEmpty(textBoxSearch.Text))
                    {
                        SearchText();
                        return;
                    }

                    var find = from f in productInList select f;
                    if (!string.IsNullOrEmpty(checkComboBoxBrand.SelectedValue))
                        find = from f in find
                               where checkComboBoxBrand.SelectedValue.Contains(f._BrandId.ToString())
                               select f;

                    if (!string.IsNullOrEmpty(checkComboBoxGroupS.SelectedValue))
                        find = from f in find
                               where checkComboBoxGroupS.SelectedValue.Contains(f._GroupSId.ToString())
                               select f;

                    if (!string.IsNullOrEmpty(checkComboBoxPlace.SelectedValue))
                        find = from f in find
                               where checkComboBoxPlace.SelectedValue.Contains(f._PlaceId.ToString())
                               select f;

                    dataGridObject.ItemsSourceNoCalc = find;
                    break;

                case Flag.盘点准备单: 
                   productInList= FillProductS(Table.ProductS.GetListInStoreS(uCStoreS1.SelectedObjectId,null));
                   dataGridObject.ItemsSourceNoCalc = productInList;
                    break;
            }
        }

        private void SearchText()
        {
            var find = from f in productInList
                       where f._Name.Contains(textBoxSearch.Text) || f._Code.Contains(textBoxSearch.Text) || f._Barcode.Contains(textBoxSearch.Text)
                       select f;

            dataGridObject.ItemsSourceNoCalc = find;
            textBoxSearch.Clear();
        }

        private List<TempClass> FillProductS(ObservableCollection<Table.ProductS> productS)
        {
            if (productS == null)
                return null;

            var find = from f in productS select f;
            if (!string.IsNullOrEmpty(checkComboBoxBrand.SelectedValue))
                find = from f in find where checkComboBoxBrand.SelectedValue.Contains(f.BrandId.ToString()) select f;
            if (!string.IsNullOrEmpty(checkComboBoxGroupS.SelectedValue))
                find = from f in find where checkComboBoxGroupS.SelectedValue.Contains(f.GroupSId.ToString()) select f;
            if (!string.IsNullOrEmpty(checkComboBoxPlace.SelectedValue))
                find = from f in find where checkComboBoxPlace.SelectedValue.Contains(f.PlaceId.ToString()) select f;

            List<TempClass> obj = new List<TempClass>();
            foreach (Table.ProductS p in find)
            {
                TempClass tf = new TempClass()
                {
                    _QuantityOld = p._Quantity,
                    _Name = p.Name,
                    _Barcode = p.Barcode,
                    _Code = p.Code,
                    _BrandName = p._BrandName,
                    _PlaceName = p._PlaceName,
                    _UnitName = p._UnitName,
                    _Standard = p.Standard,
                    _AveragePrice = p._AveragePrice,
                     _ProductSId=p.Id,
                      _BrandId=p.BrandId,
                       _GroupSId=p.GroupSId,
                        _PlaceId=p.PlaceId,
                };
                obj.Add(tf);
            }
            return obj;
        }

        private void PrintOrSave()
        {
            switch (flag)
            {
                case Flag.开始盘点:
                    foreach (TempClass p in productInList)
                        order.ProductSList.First(f => f.ProductSId == p._ProductSId).QuantityNew = p._QuantityNew ;
                 
                    MessageWindow.Show(order.Update().ToString());
                    break;

                case Flag.盘点准备单:
                    //PrintFunction.PrintList(dataGridObject.DataGrid, DataTableText.盘点单);
                    break;
            }
        }



        public class TempClass
        {
            public Int64 _ProductSId { get; set; }
            public double _QuantityOld { get; set; }
            ulong quantityNew = 0;
            public ulong _QuantityNew { get { return quantityNew; } set { quantityNew = value; } }
            public string _PlaceName
            {
                get;
                set;
            }
            public string _BrandName
            {
                get;
                set;
            }
            public string _Code
            {
                get;
                set;
            }
            public string _Name
            {
                get;
                set;
            }
            public string _Standard
            {
                get;
                set;
            }
            public string _UnitName
            {
                get;
                set;
            }
            public string _Barcode
            {
                get;
                set;
            }
            public Int64 _GroupSId { get; set; }
            public Int64 _BrandId { get; set; }
            public Int64 _PlaceId { get; set; }
            public double _AveragePrice { get; set; }
        }
    }
}